import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import type { IDialog } from './types'
import { AIStatusEnum, RecorderTypeEnum } from './types.d'
import { requestAI } from './api'
import { handleCopyToClipboard } from './util'
import { message } from 'ant-design-vue'

export const useChatBotStore = defineStore('chatBot', () => {
  /*--- 变量 ---*/
  // 当前是否正在请求AI接口
  const aiLoading = ref(false)
  // 对话列表
  const dialogList = ref<IDialog[]>([])
  // 用户当前输入
  const userInput = ref('')
  // 初始化对话框
  const initDialogList = ref<IDialog[]>([{
    user: null,
    ai: {
      content: `### **您好，我是您的智能助理**
- 我可以基于语音录制的转写内容回答问题，如总结病历文书等。

- 我的回答由AI生成，仅供参考。

- 点击开始录音。
`,
      status: AIStatusEnum.init
    }
  }])

  /*--- 方法 ---*/
  // 清除用户输入
  const clearUserInput = () => {
    userInput.value = ''
  }
  // 复制AI生成内容
  const copyToClipboard = (index: number) => {
    const content = dialogList.value[index]?.ai.content
    handleCopyToClipboard(content).then(
      () => {
        message.success('复制成功')
      },
      () => {
        message.success('复制失败')
      }
    )
  }
  // 重新生成
  const reGenerate = (index: number, customCallback?: () => void) => {
    console.log(customCallback)
    getAIAnswer(dialogList.value[index].user.content?.text || dialogList.value[index].user.content, customCallback)
  }
  // 处理AI结果
  const handleAIResponse = (type: AIStatusEnum, content?: null | string) => {
    const latestDialog = dialogList.value[dialogList.value.length - 1]
    switch (type) {
      case AIStatusEnum.loading:
        latestDialog.ai.content += content
      case AIStatusEnum.success:
      case AIStatusEnum.fail:
        latestDialog.ai.status = type
        break
    }
  }
  // 调用AI能力
  const getAIAnswer = async (inputContent?: string, customCallback?: () => void) => {
    const input = (inputContent ?? userInput.value) + "。根据上面的问诊对话自动生成对应的电子病历，电子病历分为主诉, 现病史,  既往史，只生成这三个章节。答"
    
    if (!inputContent) {
      dialogList.value.push({
        user: {
          content: input
        },
        ai: {
          content: '',
          status: AIStatusEnum.loading
        }
      })
      clearUserInput()
    } else {
      const ai = dialogList.value[dialogList.value.length - 1].ai
      ai.content = ''
      ai.status = AIStatusEnum.loading
    }
    requestAI(
      input,
      (content) => {
        handleAIResponse(AIStatusEnum.loading, content)
        customCallback?.()
      },
      () => handleAIResponse(AIStatusEnum.success),
      () => handleAIResponse(AIStatusEnum.fail)
    )
  }

  return {
    aiLoading,
    dialogList,
    userInput,
    initDialogList,
    getAIAnswer,
    copyToClipboard,
    reGenerate,
  }
})
